<template>
  <el-dialog title="分配角色" :visible.sync="showRoleDialog" @close="btnCancel">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="roleIds">
      <!-- 选项 -->
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  data() {
    return {
      showRoleDialog: false,
      userId: null,
      list: [],
      roleIds: []
    }
  },
  methods: {
    async getRoleList() {
      const { rows } = await getRoleList()
      this.list = rows
    },
    async getUserDetailById(id) {
      const { roleIds } = await getUserDetailById(id)
      this.userId = id
      this.roleIds = roleIds
    },
    async btnOk() {
      if (this.roleIds.length === 0) {
        this.$message.warning('请选择至少一个角色')
        return
      }
      try {
        await assignRoles({
          id: this.userId,
          roleIds: this.roleIds
        })
        this.$message.success('分配角色成功')
        this.showRoleDialog = false
      } catch (error) {
        console.log(error)
        this.$message.error('分配角色失败')
      }
    },
    btnCancel() {
      this.roleIds = []
      this.showRoleDialog = false
    }
  }
}
</script>

<style>

</style>
